import request from '@/utils/request'
import type {
  MenuDTO,
  MenuQueryRequest,
  PageResponse,
  ApiResponse,
  UserMenuResponse
} from '@/types/api'

// 菜单管理API
export const menuApi = {
  // 创建菜单
  createMenu: (data: MenuDTO): Promise<ApiResponse<MenuDTO>> => {
    return request.post('/menus', data)
  },

  // 更新菜单
  updateMenu: (menuId: string, data: MenuDTO): Promise<ApiResponse<MenuDTO>> => {
    return request.put(`/menus/${menuId}`, data)
  },

  // 获取菜单详情
  getMenu: (menuId: string): Promise<ApiResponse<MenuDTO>> => {
    return request.get(`/menus/${menuId}`)
  },

  // 删除菜单
  deleteMenu: (menuId: string): Promise<ApiResponse<void>> => {
    return request.delete(`/menus/${menuId}`)
  },

  // 分页查询菜单
  queryMenus: (params: MenuQueryRequest): Promise<ApiResponse<PageResponse<MenuDTO>>> => {
    return request.get('/menus', { params })
  },

  // 获取所有菜单
  getAllMenus: (): Promise<ApiResponse<MenuDTO[]>> => {
    return request.get('/menus/all')
  },

  // 根据类型获取菜单
  getMenusByType: (menuType: string): Promise<ApiResponse<MenuDTO[]>> => {
    return request.get(`/menus/type/${menuType}`)
  },

  // 获取菜单树
  getMenuTree: (): Promise<ApiResponse<MenuDTO[]>> => {
    return request.get('/menus/tree')
  },

  // ❌ 已删除: getVisibleMenuTree - 登录接口已直接返回树形菜单，无需额外调用

  // 获取用户菜单树
  getUserMenuTree: (userId: string): Promise<ApiResponse<MenuDTO[]>> => {
    return request.get(`/menus/tree/user/${userId}`)
  },

  // 获取子菜单
  getChildMenus: (menuId: string): Promise<ApiResponse<MenuDTO[]>> => {
    return request.get(`/menus/${menuId}/children`)
  },

  // 获取菜单权限
  getMenuPermissions: (menuId: string): Promise<ApiResponse<string[]>> => {
    return request.get(`/menus/${menuId}/permissions`)
  },

  // 分配菜单权限
  assignMenuPermissions: (menuId: string, permissionIds: string[]): Promise<ApiResponse<void>> => {
    return request.post(`/menus/${menuId}/permissions`, permissionIds)
  },

  // 更新菜单状态
  updateMenuStatus: (menuId: string, status: number): Promise<ApiResponse<void>> => {
    return request.put(`/menus/${menuId}/status`, null, {
      params: { status }
    })
  },

  // 更新菜单可见性
  updateMenuVisibility: (menuId: string, visible: boolean): Promise<ApiResponse<void>> => {
    return request.put(`/menus/${menuId}/visible`, null, {
      params: { visible }
    })
  },

  // 获取菜单统计信息
  getMenuStatistics: (): Promise<ApiResponse<{
    totalMenus: number
    enabledMenus: number
    disabledMenus: number
    visibleMenus: number
    hiddenMenus: number
    directoryMenus: number
    pageMenus: number
    buttonMenus: number
    rootMenus: number
    childMenus: number
  }>> => {
    return request.get('/menus/statistics')
  }
}

export default menuApi
